package com.lv.suyiyong.hfr.ui

import android.graphics.Typeface
import android.text.TextUtils
import android.view.View
import androidx.activity.viewModels
import androidx.core.widget.addTextChangedListener
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.viewpager2.widget.ViewPager2
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.KeyboardUtils
import com.blankj.utilcode.util.SizeUtils
import com.google.android.material.tabs.TabLayoutMediator
import com.lv.common.adapter.ViewPager2Adapter
import com.lv.common.base.BaseActivity
import com.lv.common.bean.CommonSelectedBean
import com.lv.common.ktx.initSingleClickListener
import com.lv.common.ktx.setSelectedTabIndicatorFixWidth
import com.lv.common.network.model.DataResult
import com.lv.common.utils.ARoutUtils
import com.lv.common.utils.Constants
import com.lv.common.utils.StatusBarUtil
import com.lv.common.utils.showToast
import com.lv.service.bean.CommonTab
import com.lv.service.bean.GoodsBean
import com.lv.service.bean.SearchBean
import com.lv.service.model.EditorViewModel
import com.lv.service.model.ServiceViewModel
import com.lv.service.network.BaseYgxRsp
import com.lv.service.network.onBizError
import com.lv.service.network.onBizOK
import com.lv.service.network.onFailure
import com.lv.service.network.onSuccess
import com.lv.service.repo.HomeSearch
import com.lv.service.repo.HomeSearchDbHelper
import com.lv.service.utils.YgxToolsKt
import com.lv.suyiyong.hfr.R
import com.lv.suyiyong.hfr.adapter.SearchGoodsAdapter
import com.lv.suyiyong.hfr.databinding.ActivityHomeSearchResultBinding
import com.lv.suyiyong.hfr.fragment.CompanyCategoryLRFragment
import com.lv.suyiyong.hfr.fragment.CompanyProductChildFragment
import com.lv.suyiyong.hfr.fragment.CompanyProductChildVFragment
import com.lv.suyiyong.hfr.fragment.HomeSearchFactoryFragment
import com.lv.suyiyong.hfr.fragment.HomeSearchGoodsFragment
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.withContext
import org.koin.androidx.viewmodel.ext.android.viewModel

/**
 * 作者： ygx
 * 创建日期：2023/5/6 10:33 AM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 * <p>
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：首页搜索结果页面
 */
@Route(path = ARoutUtils.HomeSearchResultActivity)
class HomeSearchResultActivity : BaseActivity<ActivityHomeSearchResultBinding>(),
    View.OnClickListener {
    @Autowired(name = "search")
    @JvmField
    var search: String = ""

    private val mTabs: MutableList<String> =
        mutableListOf<String>("店铺", "工厂店", "品牌店", "附近", "商品")
    private val mFragments = mutableListOf<Fragment>()
    private var mCpyid: String = ""
    private var mCurrentTab: Int = 0
    private var mFcaid: String = ""
    private var page: Int = 1
    private var pageSize: Int = Constants.pageSize
    private val mParmasMap = mutableMapOf<String, String>()

    private val mEditorViewModel by viewModels<EditorViewModel>()
    private val myScope: CoroutineScope = CoroutineScope(SupervisorJob())
    private val serviceViewModel: ServiceViewModel by viewModel()
    override fun getLayoutRes() = R.layout.activity_home_search_result
    override fun initView() {
        super.initView()
        initStatusBar(this, true, true)
        ARouter.getInstance().inject(this)
        mBinding.apply {
            StatusBarUtil.setHeightAndPadding(this@HomeSearchResultActivity, viewTop)
            initSingleClickListener(ivBackTop, ivDelete, viewSearch)
        }
    }


    override fun initConfig() {
        super.initConfig()

        if (search.isNotEmpty()) {
            mBinding.searchVM = search
        }
        initTabAdapter()
    }

    private fun initTabAdapter() {

    }


    override fun initData() {
        super.initData()
        initFragment()
    }

    private fun initFragment() {
        mFragments.clear()
        mFragments.add(HomeSearchFactoryFragment.newInstance(0))
        mFragments.add(HomeSearchFactoryFragment.newInstance(1))
        mFragments.add(HomeSearchFactoryFragment.newInstance(2))
        mFragments.add(HomeSearchFactoryFragment.newInstance(3))
        mFragments.add(HomeSearchGoodsFragment.newInstance(4))
        val mTabAdapter = ViewPager2Adapter(
            supportFragmentManager, lifecycle, mTabs,
            object : ViewPager2Adapter.TabPagerListener {
                override fun getFragment(position: Int): Fragment {
                    return mFragments[position]
                }

            }
        )
        mBinding.viewPager.adapter = mTabAdapter
        TabLayoutMediator(mBinding.tabLayout, mBinding.viewPager) { tab, position ->
            tab.text = mTabs[position]
        }.attach()

        mBinding.viewPager.offscreenPageLimit = mTabs.size
        mBinding.tabLayout.setSelectedTabIndicatorFixWidth(SizeUtils.dp2px(33.0f).toFloat())
        mBinding.tabLayout.addOnTabSelectedListener(YgxToolsKt.setSelectedBoldTab())

        val selecTab = mTabs[mCurrentTab]
        val spannedString = YgxToolsKt.setTextSpan(selecTab, Typeface.BOLD)
        mBinding.tabLayout.getTabAt(mCurrentTab)?.text = spannedString
        setCurrentFragment(mCurrentTab)
        mBinding.viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                mCurrentTab = position
                val toString = mBinding.etSearch.text.trim().toString()
                saveSearchWord(toString)
//                mEditorViewModel.obCommon.postValue(CommonTab(toString, tag = mCurrentTab))
            }
        })
        saveSearchWord(search)
    }

    fun setCurrentFragment(current: Int) {
        mBinding.viewPager.currentItem = current
    }


    override fun initEvents() {
        super.initEvents()

        mBinding.etSearch.setOnEditorActionListener { v, actionId, event ->
            KeyboardUtils.hideSoftInput(mBinding.etSearch)
            search = mBinding.etSearch.text.toString().trim()
            if (TextUtils.isEmpty(search)) {
                showToast("请输入要搜索的商品/门店")
                false
            } else {
                saveSearchWord(search)
                true
            }
        }

        mBinding.etSearch.addTextChangedListener { text ->
            if (TextUtils.isEmpty(text)) {
                search = ""
                mBinding.etSearch.paint.isFakeBoldText = false
            } else {
                search = text.toString()
                mBinding.etSearch.paint.isFakeBoldText = true
            }
        }

    }

    private fun saveSearchWord(searchWord: String) {
        if (search != searchWord && searchWord.isNotEmpty()) {
            val homeSearch = HomeSearch(searchWord, searchWord, false)
            HomeSearchDbHelper.insertHomeSearch(this@HomeSearchResultActivity, homeSearch)
            search = searchWord
        }
        mEditorViewModel.obCommon.postValue(CommonTab(search, tag = mCurrentTab))
        //发消息通知列表刷新
//        LiveEventBus
//            .get(LiveEventUtils.REFRESH_SEARCH_PAGE_KEY, String::class.java)
//            .post("HomeSearchActivity")
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.iv_back_top -> finish()
            R.id.iv_delete -> {
                mBinding.searchVM = ""
                search = ""
            }

            R.id.view_search -> {
                mBinding.searchVM = ""
                mBinding.etSearch.setText(search)
                mBinding.etSearch.setSelection(search.length)
            }

        }
    }


}